#include <sys/socket.h>
#include <sys/types.h>
#include <iostream>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include "Log.hpp"

using namespace log_ddsm;

// 接收缓冲区大小
enum
{
    SIZE = 2048
};

// 客户端主逻辑：发送信息并接受到服务器传递回来的信息
// ./udpserver serverip serverpost
int main(int args, char *argv[])
{
    // 对传入参数个数进行讨论
    if (args != 3)
    {
        std::cerr << "Usage: " << argv[0] << " ip " << "port" << std::endl;
        exit(0);
    }

    std::string localip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    // 创建一个以UDP形式传输数据的网络套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    // 填充接收到的服务器信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(localip.c_str());

    // 客户端首先需要发送一个消息，服务器收到消息之后回显
    while (true)
    {
        // 拼接消息内容
        std::string mes;
        std::cout << "Please Enter # ";
        std::getline(std::cin, mes);

        int n = sendto(sockfd, mes.c_str(), mes.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            LOG(ERROR, "sendto fail!\n");
            exit(-1);
        }
        struct sockaddr_in tem;
        socklen_t len = sizeof(tem);

        char buf[SIZE] = {0};
        n = recvfrom(sockfd, buf, sizeof(buf)-1, 0, (struct sockaddr *)&tem, &len);
        if (n > 0)
        {
            buf[n] = '\0';
            std::cout << buf << std::endl;
        }
        else
        {
            break;
        }
    }

    return 0;
}
